//
//  HJShareManager.m
//  Sneakers
//
//  Created by 胡光健 on 2017/10/10.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HJShareManager.h"
#define ShareAppKey  @"217f7da690fb0"
#define ShareAppSecret  @"3e4b9703f5ba76a901702aacd05f75c8"

@implementation HJShareManager

+(instancetype)manager {
     static HJShareManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

-(void)registerShareSDK {
    [ShareSDK registerActivePlatforms:@[
                                        @(SSDKPlatformTypeSinaWeibo),
                                        @(SSDKPlatformTypeWechat),
                                        @(SSDKPlatformTypeQQ),
                                        @(SSDKPlatformSubTypeWechatSession),
                                        @(SSDKPlatformSubTypeWechatTimeline),
                                        ]
    onImport:^(SSDKPlatformType platformType) {
         switch (platformType) {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformSubTypeWechatSession:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformSubTypeWechatTimeline:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
                 
             default:
                 break;
         }
     } onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
         switch (platformType) {
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:@""
                                           appSecret:@""
                                         redirectUri:@""
                                            authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wx77ce449425419979"
                                       appSecret:@"35e9ba0428de3f87bdf19e6151e586a2"];
                 break;
             case SSDKPlatformSubTypeWechatSession:
                 [appInfo SSDKSetupWeChatByAppId:@"wx77ce449425419979" appSecret:@"35e9ba0428de3f87bdf19e6151e586a2" backUnionID:YES];
                 break;
             case SSDKPlatformSubTypeWechatTimeline:
                 [appInfo SSDKSetupWeChatByAppId:@"wx77ce449425419979" appSecret:@"35e9ba0428de3f87bdf19e6151e586a2" backUnionID:YES];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:@"1106622738"
                                      appKey:@"KLlgxkSGqrJIst09"
                                    authType:SSDKAuthTypeBoth];
                 break;
            default:
                 break;
        }
    }];
}

-(void)share:(SSDKPlatformType)type title:(NSString *)title content:(NSString *)content url:(NSString *)url imageUrlStr:(NSString *)imageUrlStr {
    // 不管外界传的imageUrlStr是NSStrin，还是NSUrl,都能正常运行
    NSURL *shareImgUrl;
    if ([imageUrlStr isKindOfClass:[NSURL class]]) {
        shareImgUrl = (NSURL *)imageUrlStr;
    } else {
        shareImgUrl = [NSURL URLWithString:imageUrlStr];
    }
    // 配置分享参数
    UIImage *shareImage;
    if (url.length < 3) { // 1. 没有定义shareUrl,默认分享宣传链接
        shareImage = [UIImage imageNamed:@"icon2"];
        url = @"";
    } else if (shareImgUrl.absoluteString.length < 2) { // 2. 有url但是没有图片，默认给icon
        shareImage = [UIImage imageNamed:@"icon2"];
    } else if (![shareImgUrl.absoluteString containsString:@"http"]) { // 3. 有图片，但是是本地的
        shareImage = [UIImage imageNamed:shareImgUrl.absoluteString];
    } else { // 4. 有url也有图片
        NSData *imageData = [NSData dataWithContentsOfURL:shareImgUrl];
        CGFloat scale =  1 / (imageData.length / 1024.0 / 32.0);
        scale = scale > 1.0 ? 1.0 : scale;
        shareImage = [UIImage imageWithData:imageData scale:scale];
    }
    title = [title stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    title = [title stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    title = title.length > 35 ? [title substringToIndex:34] : title;
    content = [content stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    content = [content stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    content = content.length > 40 ? [content substringToIndex:39] : content;
    
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKEnableUseClientShare];
    [shareParams SSDKSetupShareParamsByText:content images:@[shareImage] url:[NSURL URLWithString:url] title:title type:SSDKContentTypeAuto];
    
    if (type == SSDKPlatformTypeSinaWeibo) {
        BOOL ret = [ShareSDK hasAuthorized:SSDKPlatformTypeSinaWeibo];
        if (ret) {
            [[UIViewController currentViewController] showTextHUDWithStr:@"分享中..."];
        }
    }
    [ShareSDK share:type parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
        if (state == SSDKResponseStateSuccess) {
            [[UIViewController currentViewController] showSuccessHUDWithStr:@"分享成功"];
        } else if (state == SSDKResponseStateFail) {
            NSLog(@"分享失败! %@",error);
            [[UIViewController currentViewController] showErrorHUDWithError:@"分享失败"];
        } else if (state == SSDKResponseStateCancel) {
            NSLog(@"取消分享 %@",userData);
            [[UIViewController currentViewController] showErrorHUDWithError:@"取消分享"];
        }
        [[UIViewController currentViewController] hideTextHud];
    }];
}


/**登录*/
-(void)shareLogin:(SSDKPlatformType)type tag:(NSString *)tag success:(void (^)(NSDictionary *))success {
    [ShareSDK getUserInfo:type onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
        [[UIViewController currentViewController] hideTextHud];
        if (state == SSDKResponseStateSuccess) {
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            params[@"plant_msg"] = user.uid;
            params[@"type"] = tag;
            params[@"nickname"] = user.nickname;
            params[@"avatar_path"] = user.icon;
            params[@"client_id"] = [mUserDefaults objectForKey:@"client_id"];
            [self didThirdLoginSuccessWithParams:params success:success];
        } else {
            [[UIViewController currentViewController] showSuccessHUDWithStr:@"授权失败"];
        }
    }];
}

-(void)didThirdLoginSuccessWithParams:(NSMutableDictionary *)params success:(void (^)(NSDictionary *))successsss {
    
    [TZHttpTool post:PlantLogin params:params success:^(NSDictionary *result) {
        [HJUserManager setUserModelWithDict:result[@"data"]];
        // 登录环信
        [HJEaseManager loginChatClientWithCompletion:^(BOOL success) {
            [[UIViewController currentViewController] hideTextHud];
            if (success) {
                successsss(result);
            } else {
                successsss(result);
            }
        }];
    } failure:^(NSString *msg) {
        
    }];
}
@end
